package pluginMain;

import java.io.File;
import java.io.IOException;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.event.player.PlayerDropItemEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerPickupItemEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.Inventory;
import org.bukkit.plugin.java.JavaPlugin;

public class QuickMenu extends JavaPlugin
  implements Listener
{
  public void onEnable()
  {
    getServer().getPluginManager().registerEvents(this, this);
  }
  @EventHandler(priority=EventPriority.MONITOR)
  public void join(PlayerJoinEvent e) {
    File file = new File(getDataFolder(), "config.yml");
    if (file.exists())
    {
      FileConfiguration config = YamlConfiguration.loadConfiguration(file);
      if (config.contains("Item"))
      {
        ItemStack item = config.getItemStack("Item");
        if (e.getPlayer().getInventory().getItem(8) == null)
        {
          ItemStack i = e.getPlayer().getInventory().getItem(8);
          e.getPlayer().getInventory().setItem(8, item);
          if (i != null)
            e.getPlayer().getInventory().addItem(new ItemStack[] { i });
        }
        else if (e.getPlayer().getInventory().getItem(8).getType() == Material.AIR)
        {
          ItemStack i = e.getPlayer().getInventory().getItem(8);
          e.getPlayer().getInventory().setItem(8, item);
          if (i.getType() != Material.AIR)
            e.getPlayer().getInventory().addItem(new ItemStack[] { i });
        }
        else if (!e.getPlayer().getInventory().getItem(8).equals(item))
        {
          ItemStack i = e.getPlayer().getInventory().getItem(8);
          e.getPlayer().getInventory().setItem(8, item);
          e.getPlayer().getInventory().addItem(new ItemStack[] { i });
        }
      }
    }
  }

  @EventHandler
  public void inter(PlayerInteractEvent e) {
    String lr = null;
    if ((e.getAction() == Action.LEFT_CLICK_AIR) || (e.getAction() == Action.LEFT_CLICK_BLOCK))
      lr = "Left";
    else if ((e.getAction() == Action.RIGHT_CLICK_AIR) || (e.getAction() == Action.RIGHT_CLICK_BLOCK))
      lr = "Right";
    if (lr != null)
    {
      File file = new File(getDataFolder(), "config.yml");
      if (file.exists())
      {
        FileConfiguration config = YamlConfiguration.loadConfiguration(file);
        if (config.contains("Item"))
        {
          ItemStack item = config.getItemStack("Item");
          if ((!e.getPlayer().isOp()) && 
            (e.getPlayer().getInventory().getItem(8) != null) && 
            (e.getPlayer().getInventory().getItem(8).getType() != Material.AIR) && 
            (!e.getPlayer().getInventory().getItem(8).equals(item)))
          {
            ItemStack i = e.getPlayer().getInventory().getItem(8);
            e.getPlayer().getInventory().setItem(8, item);
            e.getPlayer().getInventory().addItem(new ItemStack[] { i });
          }
          if (e.getPlayer().getItemInHand().equals(config.getItemStack("Item")))
          {
            if ((config.contains(lr)) && (config.contains(lr + "_PC")))
            {
              String command = config.getString(lr);
              boolean pc = config.getBoolean(lr + "_PC");
              if (pc)
              {
                e.getPlayer().chat("/" + command.replace("%player%", e.getPlayer().getName()));
              }
              else
              {
                Bukkit.dispatchCommand(Bukkit.getConsoleSender(), command.replace("%player%", e.getPlayer().getName()));
              }
            }
          }
        }
      }
    }
  }

  @EventHandler
  public void click(InventoryClickEvent e) {
    File file = new File(getDataFolder(), "config.yml");
    if (file.exists())
    {
      FileConfiguration config = YamlConfiguration.loadConfiguration(file);
      if (config.contains("Item"))
      {
        ItemStack item = config.getItemStack("Item");
        if (e.getSlot() == 8)
        {
          if (e.getCurrentItem() == null)
            return;
          if (e.getCurrentItem().getType() == Material.AIR)
            return;
          if (!e.getCurrentItem().equals(item))
          {
            if (!e.getWhoClicked().isOp())
            {
              e.getWhoClicked().getInventory().setItem(8, item);
            }

          }
          else if (!e.getWhoClicked().isOp())
            e.setCancelled(true);
        }
      }
    }
  }

  @EventHandler
  public void drop(PlayerDropItemEvent e) {
    if (e.getPlayer().isOp())
      return;
    File file = new File(getDataFolder(), "config.yml");
    if (file.exists())
    {
      FileConfiguration config = YamlConfiguration.loadConfiguration(file);
      if (config.contains("Item"))
      {
        ItemStack item = config.getItemStack("Item");
        if (e.getItemDrop().getItemStack().equals(item))
        {
          e.getItemDrop().remove();
          if (e.getPlayer().getInventory().getItem(8) == null)
          {
            ItemStack i = e.getPlayer().getInventory().getItem(8);
            e.getPlayer().getInventory().setItem(8, item);
            if (i != null)
              e.getPlayer().getInventory().addItem(new ItemStack[] { i });
          }
          else if (e.getPlayer().getInventory().getItem(8).getType() == Material.AIR)
          {
            ItemStack i = e.getPlayer().getInventory().getItem(8);
            e.getPlayer().getInventory().setItem(8, item);
            if (i.getType() != Material.AIR)
              e.getPlayer().getInventory().addItem(new ItemStack[] { i });
          }
          else if (!e.getPlayer().getInventory().getItem(8).equals(item))
          {
            ItemStack i = e.getPlayer().getInventory().getItem(8);
            e.getPlayer().getInventory().setItem(8, item);
            e.getPlayer().getInventory().addItem(new ItemStack[] { i });
          }
        }
      }
    }
  }

  @EventHandler
  public void pickup(PlayerPickupItemEvent e) {
    if (e.getPlayer().isOp())
      return;
    File file = new File(getDataFolder(), "config.yml");
    if (file.exists())
    {
      FileConfiguration config = YamlConfiguration.loadConfiguration(file);
      if (config.contains("Item"))
      {
        ItemStack item = config.getItemStack("Item");
        if (e.getItem().getItemStack().equals(item))
          e.setCancelled(true); 
      }
    }
  }

  @EventHandler
  public void death(PlayerDeathEvent e) {
    File file = new File(getDataFolder(), "config.yml");
    if (file.exists())
    {
      FileConfiguration config = YamlConfiguration.loadConfiguration(file);
      if (config.contains("Item"))
      {
        ItemStack i = config.getItemStack("Item");
        for (ItemStack item : e.getDrops())
        {
          if (!item.equals(i))
            continue;
          e.getDrops().remove(i);
          return;
        }
      }
    }
  }

  @EventHandler
  public void respawn(PlayerRespawnEvent e) {
    File file = new File(getDataFolder(), "config.yml");
    if (file.exists())
    {
      FileConfiguration config = YamlConfiguration.loadConfiguration(file);
      if (config.contains("Item"))
      {
        ItemStack i = config.getItemStack("Item");
        SleepThread myThead = new SleepThread(e.getPlayer().getInventory() , i);  
        Thread thread = new Thread(myThead);  
        thread.start();  
      }
    }
  }

  public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
    if (args.length == 0)
      return help(sender);
    if (args[0].equalsIgnoreCase("item"))
    {
      if (!(sender instanceof Player))
      {
        sender.sendMessage("��a��ָ��ֻ�������ʹ��");
        return true;
      }
      File file = new File(getDataFolder(), "config.yml");
      if (!file.getParentFile().exists())
        file.getParentFile().mkdirs();
      if (!file.exists())
        try {
          file.createNewFile(); } catch (IOException e) {
          e.printStackTrace();
        }
      FileConfiguration config = YamlConfiguration.loadConfiguration(file);
      Player player = (Player)sender;
      ItemStack item = player.getItemInHand();
      if (item == null)
      {
        sender.sendMessage("��a���ϵ���Ʒ����Ϊ��");
        return true;
      }
      if (item.getType() == Material.AIR)
      {
        sender.sendMessage("��a���ϵ���Ʒ����Ϊ��");
        return true;
      }
      config.set("Item", item);
      try { config.save(file); } catch (IOException e) {
        e.printStackTrace();
      }sender.sendMessage("��a���óɹ�");
      return true;
    }
    if ((args[0].equalsIgnoreCase("left")) || (args[0].equalsIgnoreCase("right")))
    {
      if (args.length < 3)
      {
        sender.sendMessage("��a/qm " + args[0].toLowerCase() + " <player/console> <ָ��> �������ʱָ��");
        return true;
      }
      if ((!args[1].equalsIgnoreCase("player")) && (!args[1].equalsIgnoreCase("console")))
      {
        sender.sendMessage("��a" + args[1] + "�Ĳ����Ĵ����,ֻ��Ϊplayer��console");
        return true;
      }
      String lr = null;
      if (args[0].equalsIgnoreCase("left"))
        lr = "Left";
      else
        lr = "Right";
      boolean pc = args[1].equalsIgnoreCase("player");
      StringBuilder sb = new StringBuilder();
      for (int x = 2; x < args.length; x++)
      {
        sb.append(args[x]);
        if (x != args.length - 1)
          sb.append(" ");
      }
      String command = sb.toString();
      File file = new File(getDataFolder(), "config.yml");
      if (!file.getParentFile().exists())
        file.getParentFile().mkdirs();
      if (!file.exists())
        try {
          file.createNewFile(); } catch (IOException e) {
          e.printStackTrace();
        }
      FileConfiguration config = YamlConfiguration.loadConfiguration(file);
      config.set(lr, command);
      config.set(lr + "_PC", Boolean.valueOf(pc));
      try { config.save(file); } catch (IOException e) {
        e.printStackTrace();
      }sender.sendMessage("��a���óɹ�");
      return true;
    }
    return true;
  }

  public boolean help(CommandSender sender) {
    sender.sendMessage("��a/qm item  �������ϵ���ƷΪ���һ�����Ʒ");
    sender.sendMessage("��a/qm left <player/console> <ָ��> �������ʱָ��,�����/");
    sender.sendMessage("��a/qm right <player/console> <ָ��> �����Ҽ�ʱָ��,�����/");
    sender.sendMessage("��a<player/console> playerΪ���ִ��,consoleΪ����ִ̨��,%player%Ϊ�������");
    return true;
  }
}

class SleepThread implements Runnable  
{  
	Inventory i;
	ItemStack s;
	public SleepThread(Inventory _i , ItemStack _s){
		i = _i;
		s = _s;
	}
	
    public void run()  
    {  
        try  
        {  
            Thread.sleep(3000);  
        }  
        catch (InterruptedException e)  
        {  
        }  
        
        i.setItem(8, s);
    }  
}  
